package com.cms.meeting.interceptor;

import com.cms.meeting.entity.Employee;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class PermissIntercepor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        AntPathMatcher pathMatcher = new AntPathMatcher();
        String requestURI = request.getRequestURI();
        if ("/".equals(requestURI) || "/doLogin".equals(requestURI) || "/register".equals(requestURI)
                || "/doReg".equals(requestURI)) {
            return true;
        }

        HttpSession session = request.getSession(true);

        Employee currentUser = (Employee) session.getAttribute("currentUser");

        if (pathMatcher.match("/admin/**", requestURI)) {
            if (currentUser != null) {
                if (currentUser.getRole() == 2) {
                    return true;
                } else {
                    response.getWriter().write("forbidden");
                    return false;
                }
            }
        } else {
            if (currentUser != null) {
                return true;
            }
        }

        response.sendRedirect("/");

        return false;
    }
}
